﻿using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;

namespace XamlaApp.Helpers
{
    public static class JSONHelper
    {
        /// <summary>
        /// Serializes a business object (class) into a Json string.
        /// </summary>
        /// <param name="input">The object to serialize.</param>
        /// <returns>Json string</returns>
        public static string ConvertObjectToJsonString(object input)
        {
            try
            {
                using (var memoryStream = new MemoryStream())
                {
                    var dataContractJsonSerializer = new DataContractJsonSerializer(input.GetType());
                    dataContractJsonSerializer.WriteObject(memoryStream, input);
                    memoryStream.Position = 0;

                    using (var streamReader = new StreamReader(memoryStream))
                        return streamReader.ReadToEnd();
                }
            }
            catch (SerializationException)
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// Deserializes a Json string into the given Type.
        /// </summary>
        /// <typeparam name="T">The target type to deserialize the Json string into.</typeparam>
        /// <param name="json">The serialized Json string.</param>
        /// <returns></returns>
        public static T ConvertJsonStringToObject<T>(string json)
        {
            try
            {
                using (var memoryStream = new MemoryStream())
                {
                    byte[] bytes = Encoding.Unicode.GetBytes(json);
                    memoryStream.Write(bytes, 0, bytes.Length);
                    memoryStream.Position = 0;

                    var dataContractJsonSerializer = new DataContractJsonSerializer(typeof (T));

                    return (T) dataContractJsonSerializer.ReadObject(memoryStream);
                }
            }
            catch (SerializationException)
            {
                return default(T);
            }
        }
    }
}